//
//  MZCamera.m
//  MTime
//
//  Created by mtime_lee on 2017/8/28.
//  Copyright © 2017年 imac. All rights reserved.
//

#import "MZCamera.h"

@interface MZCamera ()
//显示界面
@property(nonatomic,strong) UIView *preView;
//显示图层
@property(nonatomic,strong) AVCaptureVideoPreviewLayer *preViewLayer;
//拍摄会话
@property(nonatomic,strong) AVCaptureSession *session;
//输入设备
@property(nonatomic,strong) AVCaptureDeviceInput *input;
//输出图片
@property(nonatomic,strong) AVCaptureStillImageOutput *output;
//捕获设备
@property (nonatomic, strong) AVCaptureDevice *device;

@end

@implementation MZCamera

- (instancetype)initWithPreView:(UIView *)preView preViewFrame:(CGRect)frame {
    
    if (self = [super init]) {
        self.preView = preView;
        self.preView.frame = frame;
        [self _setupSession];
        /*
         UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinchGesture:)];
         
         [self.cameraPreview addGestureRecognizer:pinch];
         #pragma mark - 变焦
         - (void)handlePinchGesture:(UIPinchGestureRecognizer *)sender {
         
         
         if (sender.state == UIGestureRecognizerStateBegan) {
         self.lastScale = 1.0;
         self.lastPoint = [sender locationInView:self.cameraPreview];
         }
         
         // Scale
         CGFloat scale = 1.0 - (self.lastScale - sender.scale);
         [self.cameraPreview.layer setAffineTransform:
         CGAffineTransformScale([self.cameraPreview.layer affineTransform],
         scale,
         scale)];
         self.lastScale = sender.scale;
         
         // Translate
         CGPoint point = [sender locationInView:self.cameraPreview];
         [self.cameraPreview.layer setAffineTransform:
         CGAffineTransformTranslate([self.cameraPreview.layer affineTransform],
         point.x - self.lastPoint.x,
         point.y - self.lastPoint.y)];
         self.lastPoint = [sender locationInView:self.cameraPreview];
         }

         */
    }
    return self;
}


-(void)_setupSession {
    
    //获取输入设备
    __block AVCaptureDevice *inputDevice = nil;
    //遍历设备数组
    NSArray *arr= [AVCaptureDevice devices];
    [arr enumerateObjectsUsingBlock:^(AVCaptureDevice *device, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if (device.position == AVCaptureDevicePositionBack) {
            inputDevice = device;
            *stop = YES;
        }
    }];
    
    self.session = [[AVCaptureSession alloc]init];
    
    //创建输入设备,添加进会话
    self.input = [[AVCaptureDeviceInput alloc] initWithDevice:inputDevice error:nil];
    if([self.session canAddInput:self.input]){
        [self.session addInput:self.input];
    }
    
    //创建输出设备,添加进会话
    self.output = [[AVCaptureStillImageOutput alloc]init];
    if([self.session canAddOutput:self.output]){
        [self.session addOutput:self.output];
    }
    
    //创建显示图层
    self.preViewLayer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:self.session];
    [self.preView.layer insertSublayer:self.preViewLayer atIndex:0];
    
    //设置图层大小,锚点
    self.preViewLayer.frame = self.preView.bounds;
    self.preViewLayer.position = self.preView.center;
    
    self.preViewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    
    [self start];
}

#pragma mark - 拍照
- (void)captureImageCompletion:(void(^)(UIImage *image))completion{
    
    //获取输出设备的链接
    NSArray *arr = self.output.connections;
    if (!arr) {
        return;
    }
    AVCaptureConnection *connection = arr[0];
    
    [self.output captureStillImageAsynchronouslyFromConnection:connection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
        NSData *data = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
        UIImage *image = [UIImage imageWithData:data];

        //图片保存完成后回调
        if (completion) {
  //            [self cutImageWithImage:image];
            completion([self cutImageWithImage:image]);
        }
    }];
    
}

//切换摄像头
- (void)switchCamera {
    NSUInteger cameraCount = [[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] count];
    if (cameraCount > 1) {
        NSError *error;
        //给摄像头的切换添加翻转动画
        CATransition *animation = [CATransition animation];
        animation.duration = .5f;
        animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        animation.type = @"oglFlip";
        
        AVCaptureDevice *newCamera = nil;
        AVCaptureDeviceInput *newInput = nil;
        //拿到另外一个摄像头位置
        AVCaptureDevicePosition position = [[self.input device] position];
        if (position == AVCaptureDevicePositionFront){
            newCamera = [self cameraWithPosition:AVCaptureDevicePositionBack];
            animation.subtype = kCATransitionFromLeft;//动画翻转方向
        }
        else {
            newCamera = [self cameraWithPosition:AVCaptureDevicePositionFront];
            animation.subtype = kCATransitionFromRight;//动画翻转方向
        }
            //生成新的输入
            newInput = [AVCaptureDeviceInput deviceInputWithDevice:newCamera error:nil];
            [self.preViewLayer addAnimation:animation forKey:nil];
            if (newInput != nil) {
                [self.session beginConfiguration];
                [self.session removeInput:self.input];
                if ([self.session canAddInput:newInput]) {
                    [self.session addInput:newInput];
                    self.input = newInput;
                    
                } else {
                    
                    [self.session addInput:self.input];
                }
                [self.session commitConfiguration];
                
            } else if (error) {
                NSLog(@"toggle carema failed, error = %@", error);
            }
    }
}

/**
 裁切图片
 
 @param image 原始图片
 @return 裁切之后的图片
 */
- (UIImage *)cutImageWithImage:(UIImage *)image
{
    //开启上下文图片绘制
    UIGraphicsBeginImageContext(self.preView.frame.size);
    //获取当前上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    NSLog(@"%@",context);
    //开始绘制图片
    CGFloat width = [UIScreen mainScreen].bounds.size.width - self.preView.bounds.size.width;
    CGFloat height = [UIScreen mainScreen].bounds.size.height - self.preView.bounds.size.height;
    
    [image drawInRect:CGRectInset(self.preView.frame, - width * 0.5, - height * 0.5)];
    
    //在图片还未从上下文中获取之前送出消息通知
    //    [[NSNotificationCenter defaultCenter] postNotificationName:kDidBenginDrawWaterImageNotification object:nil];
    
    //从上下文中获取裁切好的图片
    UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
    
    //关闭上下文
    UIGraphicsEndImageContext();
    
    return resultImage;
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    
    if (error == nil) {
//        NSLog(@"保存到系统相册成功");
        
    } else {
        NSLog(@"保存到系统失败 %@",error.localizedDescription);
    }
    
}


#pragma mark - 相机捕获位置
- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position{
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice *device in devices)
        if (device.position == position){
            return device;
        }
    return nil;
}

- (void)start{
    
    [self.session startRunning];
}

- (void)stop{
    [self.session stopRunning];
}


@end
